import random
from math import ceil
import datetime
from django import db
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django.core.paginator import Paginator

from housecentapp.models import Users, Cities, Navs, Houses, HouseImg, Settings, Stoges, Tags,Orders
from housecentapp.utils.addpwd import loadpwd
from housecentapp.utils.mails import netmail
from housecentapp.utils.savehead import recevierpics
from housecentapp.utils.regtags import rtag
from housecentapp.utils.houseuti import housesget
from housecentapp.utils.getlinda import gettimelist


def nonefile(request):
    return redirect(reverse('house:index'))

def select(request):
    db.connection="select * from "

def index(request):
    try:
        msg = request.session.get('msg')
        del request.session['msg']
    except:
        msg = ""
    TopSeven = Cities.objects.order_by('-score')
    finalList=[1,2,2,2,2,1,2]
    finalDict=[]
    infos=[]
    count=0
    for info in TopSeven:
        citybox=[]
        citybox.append(info.name)
        pics=Navs.objects.filter(city=info)
        imgsrc=random.choice(pics).imgsrc
        infos.append(citybox)
        clas=finalList[count]
        if clas==1:
            mytype="long"
            margin=22.5
        elif clas==2:
            mytype="short"
            margin=10

        finalDict.append({"type":mytype,"imgsrc":imgsrc,"name":"  ".join(info.name),"margin":margin,"cityname":info.name,"msg":msg})
        count+=1
        if count==7:
            break
    useraccount = request.session.get('account', "")
    print(useraccount)
    if useraccount:
        myuser = Users.objects.get(useraccount=useraccount)
    else:
        myuser = ""
    return render(request,'index.html',{'infos':finalDict,"myuser":myuser})

def logout(request):
    del request.session["account"]
    return redirect(reverse('house:index'))

def login(request):
    if request.method=="GET":
        try:
            msg=request.session.get('msg')
            del request.session['msg']
        except:
            msg=""
        return render(request,'login.html',{"msg":msg})
    elif request.method == "POST":
        useraccount = request.POST.get('loginaccount',"")
        password = request.POST.get('userpass',"")
        print(useraccount,password)
        if password:
            password=loadpwd(password)
            print(password)
        myuser = Users.objects.filter(useraccount=useraccount,userpass=password)
        if myuser:
            request.session["account"]=useraccount
            return redirect('/index')
        else:
            msg="用户名或密码错误"
            print(useraccount,password)
            request.session["msg"] = msg
            return redirect('/login/')

def register(request):
    if request.method=="GET":
        try:
            msg=request.session.get('msg')
            del request.session['msg']
        except:
            msg=""
        return render(request,'register.html',{"msg":msg})
    elif request.method == "POST":
        useraccount = request.POST.get('useraccount', None)
        if not useraccount:
            msg='登录名不能为空'
            request.session["msg"]=msg
            return redirect('/register')
        elif len(useraccount)<6:
            msg="登录名过短"
            request.session["msg"] = msg
            return redirect('/register')
        elif Users.objects.filter(useraccount=useraccount):
            msg = "登录名已被使用"
            request.session["msg"] = msg
            return redirect('/register')
        username = request.POST.get('username', None)
        if not username:
            msg='用户名不能为空'
            request.session["msg"] = msg
            return redirect('/register')
        password = request.POST.get('password', None)
        if not password:
            msg='密码不能为空'
            request.session["msg"] = msg
            return redirect('/register')
        elif len(useraccount)<6:
            msg="密码过短"
            request.session["msg"] = msg
            return redirect('/register')
        phone = request.POST.get('phone',None)
        email = request.POST.get('email', None)
        if not password:
            msg='邮箱不能为空'
            request.session["msg"] = msg
            return redirect('/register')
        seyzm = request.session.pop('yzm', '')
        yzm = request.POST.get('yzm', '')
        if not yzm:
            msg="请输入验证码"
            request.session["msg"] = msg
            return redirect('/register')
        elif seyzm !=yzm:
            msg = "验证码错误"
            request.session["msg"] = msg
            return redirect('/register')
        userimg = request.FILES.get('userimg')
        userimg=recevierpics(userimg)
        if not userimg:
            msg="请上传头像"
            request.session["msg"] = msg
            return redirect('/register')
        password=loadpwd(password)
        user = Users(useraccount=useraccount, username=username, userphone=phone,userpass=password, useremail=email, userimg=userimg)
        user.save()
        msg = username+"注册成功"
        request.session["msg"] = msg
        request.session["account"]=useraccount
        return redirect("/index")

def email(request,emailadress):
    if request.method=="GET":
        result=netmail(emailadress)
        if result:
            request.session["yzm"]=result[0]
            return JsonResponse({"msg":"ok","remail":result[1]})
        else:
            return JsonResponse({"msg":"error"})

def myhouses(request,cityname):
    pagesize = 30
    try:
        mytype=request.GET.get("tags","")
        if mytype:
            houses=housesget(cityname,mytype)
            houselen = len(houses)
            maxpagenum = ceil(houselen / pagesize)
            request.session[cityname] = maxpagenum
        else:
            houses=housesget(cityname,"")
    except:
        pass

    try:
        start = int(request.GET.get("start",1))
    except:
        start=1
    try:
        maxpagenum = request.session.get(cityname)
        if not maxpagenum:
            houselen = len(houses)
            maxpagenum = ceil(houselen / pagesize)
            request.session[cityname] = maxpagenum
    except:
        houselen = len(houses)
        maxpagenum = ceil(houselen / pagesize)
        request.session[cityname] = maxpagenum
    try:
        nextpage=request.GET.get("next","")
        if not nextpage:
            start=start
        elif nextpage=="next":
            if start+1>=maxpagenum:
                start=start
            else:
                start+=1
        else :
            if start-1==0:
                start=start
            else:
                start-=1
    except:
        pass
    city = Cities.objects.get(name=cityname)
    city.score+=1
    city.save()
    houses = houses[(start-1)*pagesize:start*pagesize]
    cityPage=Navs.objects.filter(city=city)
    count=0
    cityImg=[]
    for city in cityPage:
        if count==0:
            Cityclass="active"
        else:
            Cityclass=""
        count+=1
        cityImg.append({"cityclass":Cityclass,"cityimg":city.imgsrc,"citycount":count,"cityname":cityname})
    rhouses=[]
    i=0
    for house in houses:
        i+=1
        rhouses.append({
            "houseimg":house.imgsrc,
            "housename":house.name[0:15]+"......",
            "houseprice":house.price,
            "houseplace":house.placename,
            "houseJ":house.lng,
            "houseW":house.lat,
            "houseid":house.id,
        })
    pages=[]
    for page in range(1,maxpagenum+1):
        pages.append(page)
    return render(request,"rwhouses.html",{"houses":rhouses,"cities":cityImg,"cityname":cityname,"tags":rtag(cityname),"pageNow":pages,"maxnum":maxpagenum,"start":start,"ytags":mytype})

def details(request,houseid):
    try:
        houses = Houses.objects.filter(id=houseid).all()
        if houses:
            try:
                msg = request.session.get('msg')
                del request.session['msg']
            except:
                msg = ""
            house_dict = {}
            for house in houses:
                lifekonws = house.lifeknows.split(',')
                house_dict["toilet"] = lifekonws[0]
                house_dict["time1"] = lifekonws[1]
                house_dict["time2"] = lifekonws[2]
                house_dict["foreign"] = lifekonws[3]
                stoges = Stoges.objects.filter(id=house.stoge_id).all()
                tags = Tags.objects.filter(houses=house).all()
                settings = Settings.objects.filter(houses=house).all()
                houseimg = HouseImg.objects.filter(house=house).all()
            houseimgs = []  # 轮播图
            for i in houseimg:
                if i.size == "big":
                    houseimgs.append(i)
            return render(request, 'details.html', locals())
        else:
            return HttpResponse('<h1>404</h1><h3>你访问的页面不见啦</h3>')
    except Exception as e:
        print('出现异常: ', e)
        return HttpResponse('你的访问出错啦')

def calculation(request):
    if request.session.get('account'):

        starttime = request.POST.get("startdate")
        endtime = request.POST.get("enddate")
        price =request.POST.get("price")
        house_id = request.POST.get("houseid")

        price=float(price)
        house_id=int(house_id)
        if not starttime:
            starttime=datetime.date.today().strftime("%Y-%m-%d")
        if not endtime:
            endtime=starttime
        timelist = gettimelist(starttime,endtime)
        print(timelist)
        user = Users.objects.get(useraccount=request.session.get('account'))
        print(house_id)
        house = Houses.objects.get(id=int(house_id))
        idlist = []
        for mytime in timelist:

            try:
                order=Orders.objects.create(startroom=mytime,house_id=house.id, user=user,ispay=0)
                idlist.append(order.id)
            except Exception as e:
                print(e)
                pass
        print(idlist)
        idstrs=",".join([str(i) for i in idlist])
        print(idstrs)
        return redirect('/order/?orderids='+idstrs)
    else:
        return redirect('/login')

def page_content(orders, number):
    #  实例化分页器对象，按每5条订单一页显示
    page1 = Paginator(orders, 5)
    page = page1.page(number)
    return page

def orders(request):  # 订单页面
    order_ids = request.GET.get('orderids')
    order_idms=order_ids.split(",")
    days = len(order_idms)

    for order_id in order_idms:
        order = Orders.objects.get(id = int(order_id))
        housei = {"name":order.house.name,"imgsrc":order.house.imgsrc,"sindecripe":order.house.sindecripe,"placename":order.house.placename,"price":order.house.price,"houseid":order.house.id}
        user = {"name":order.user.username}
        break
    yz = 50
    return render(request,'orders.html',{"ids":order_ids,"days":days,"house":housei,"user":user["name"],"allprice":order.house.price*days,"yz":50,"countmoney":order.house.price*days+50})

def user_info(request):
    try:
        msg = request.session["msg"]
        del request.session["msg"]
    except:
        msg = ""
    useraccount = request.session.get('account')
    if not useraccount:
        return redirect('/login')
    user = Users.objects.get(useraccount=useraccount)
    page_number = int(request.GET.get('page_number', 1))
    orders = Orders.objects.filter(user = user).order_by('-id')
    myorders = []
    house_id = ""
    ordertime = ""
    i=1
    for order in orders:
        housei_id = order.house.id
        if housei_id != house_id:
            house_id=housei_id
            if i!=1:
                myorders.append(orderd)
            i=2
            orderd={
                "ids":str(order.id)+",",
                "id":order.id,
                "housename":order.house.name[0:10]+".....",
                "houseid":order.house.id,
                "days":1,
                "price":order.house.price,
                "regtime":order.regtime,
                "imgsrc":order.house.imgsrc,
                "ispay":order.ispay
            }
        else:
            orderd["ids"]+=str(order.id)+","
            orderd["days"]+=1
            orderd["price"]+=order.house.price
    else:
        try:
            myorders.append(orderd)
        except:
            pass
    page = page_content(myorders,page_number)
    return render(request, 'user_info.html',{"page":page,"page_number":page_number,"orders":myorders})

def orders2(request):
    ids = request.GET.get('order_ids')
    ids = ids.split(",")
    while '' in ids:
        ids.remove('')
    ids =[int(i) for i in ids]
    i = 0
    for myid in ids:
        if i==0:
            obj = Orders.objects.get(id=myid)
            house_id = obj.house.id
            i+=1
        order= Orders.objects.get(id=myid)
        order.delete()
    return redirect(reverse('house:details',house_id))

def reinfo(request):
    ids = request.GET.get('order_id')
    ids = ids.split(",")
    while '' in ids:
        ids.remove('')
    ids = [int(i) for i in ids]
    i = 0
    for myid in ids:

        order = Orders.objects.get(id=myid)
        if i==0:
            house = Houses.objects.get(id=order.house.id)
            house_id = house.id
            i+=1
        order.ispay=1
        order.save()
    msg = "支付成功"
    request.session["msg"]=msg
    return redirect(reverse('house:userorder'))
